<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { getCurrentUser, updateUserInfo } from '@/api/user'
import type { UserUpdateForm } from '@/types/user'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()

const userForm = ref<UserUpdateForm>({
  userId: 0,
  nickname: '',
  gender: 'UNKNOWN',
  email: ''
})

const loading = ref(false)

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    loading.value = true
    const response = await getCurrentUser()
    userStore.setUserInfo(response.data)
    userForm.value = {
      userId: response.data.userId,
      nickname: response.data.nickname || '',
      gender: response.data.gender || 'UNKNOWN',
      email: response.data.email || ''
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

// 更新用户信息
const updateProfile = async () => {
  try {
    loading.value = true
    const response = await updateUserInfo(userForm.value)
    userStore.setUserInfo(response.data)
    ElMessage.success('更新成功')
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败')
  } finally {
    loading.value = false
  }
}

// 初始化加载数据
onMounted(() => {
  fetchUserInfo()
})
</script>

<template>
  <div class="profile-container">
    <el-card>
      <template #header>
        <div class="header">
          <span>个人信息</span>
        </div>
      </template>

      <el-form
        :model="userForm"
        label-width="100px"
        label-position="left"
        @submit.prevent="updateProfile"
      >
        <el-form-item label="用户名">
          <el-input v-model="userStore.userInfo?.username" disabled />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio label="MALE">男</el-radio>
            <el-radio label="FEMALE">女</el-radio>
            <el-radio label="UNKNOWN">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" native-type="submit">
            保存
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.profile-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
